package com.course.server.service.discusspost;

import com.course.server.domain.Member;
import com.course.server.domain.discusspost.Comment;
import com.course.server.domain.discusspost.DiscussPost;
import com.course.server.dto.PageDto;
import com.course.server.dto.discusspost.DiscussPostDto;
import com.course.server.dto.discusspost.DiscussPostQueryById_Z1;
import com.course.server.mapper.my.CommentMapper;
import com.course.server.mapper.my.MyDiscussPostMapper;
import com.course.server.service.MemberService;
import com.course.server.util.HostHolder;
import com.course.server.util.SensitiveFilter;
import com.course.server.util.UuidUtil;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.course.server.util.CommunityConstant.ENTITY_TYPE_COMMENT;
import static com.course.server.util.CommunityConstant.ENTITY_TYPE_POST;


@Service
public class DiscussPostService {

    private static final Logger logger = LoggerFactory.getLogger(DiscussPostService.class);

    @Autowired
    private MyDiscussPostMapper myDiscussPostMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Value("${caffeine.posts.max-size}")
    private int maxSize;

    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;

    // Caffeine核心接口: Cache, LoadingCache, AsyncLoadingCache

    // 帖子列表缓存
    private LoadingCache<String, List<DiscussPost>> postListCache;

    // 帖子总数缓存
    private LoadingCache<Integer, Integer> postRowsCache;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private MemberService memberService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private CommentMapper commentMapper;

    /**
     *
     * @param pageDto
     * @param userId userId=""表示不用userId条件过滤。
     * @param orderMode orderMode：0最新，1最热。
     * @param courseId courseId=""表示不用courseId条件过滤。
     * @return
     */
    public Map<String,Object> findDiscussPosts(PageDto pageDto,int orderMode,String userId,String courseId) {
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());
        List<DiscussPost> discussPostList = myDiscussPostMapper.selectAllDiscussPosts(orderMode,userId,courseId);
        PageInfo<DiscussPost> pageInfo = new PageInfo<>(discussPostList);
        pageDto.setTotal(pageInfo.getTotal());
        List<DiscussPostDto> discussPostDtoList=new ArrayList<>();
        for (DiscussPost discussPost : discussPostList) {
            DiscussPostDto discussPostDto=new DiscussPostDto();
            discussPostDto.setDiscussPost(discussPost);
            long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId());
            discussPostDto.setLikeCount(likeCount);
            Member member = memberService.findUserById(discussPost.getUserId());
            discussPostDto.setUser(member);
            discussPostDtoList.add(discussPostDto);
        }
        pageDto.setList(discussPostDtoList);
        Map<String,Object> dto=new HashMap<>();
        dto.put("pageDto",pageDto);
        dto.put("orderMode",orderMode);
        return dto;
    }

    public int addDiscussPost(DiscussPost post) {
        if (post == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        // 转义HTML标记
/*        post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
        post.setContent(HtmlUtils.htmlEscape(post.getContent()));*/
        post.setTitle(post.getTitle());
        post.setContent(post.getContent());
        post.setId(UuidUtil.getShortUuid());
        // 过滤敏感词
        post.setTitle(sensitiveFilter.filter(post.getTitle()));
        post.setContent(sensitiveFilter.filter(post.getContent()));

        return myDiscussPostMapper.insertDiscussPost(post);
    }

    public DiscussPostQueryById_Z1 findDiscussPostById(String discussPostId,PageDto pageDto) {

        DiscussPostQueryById_Z1 discussPostQueryById_z1=new DiscussPostQueryById_Z1();
        // 帖子
        DiscussPost post = myDiscussPostMapper.selectDiscussPostById(discussPostId);
        discussPostQueryById_z1.setDiscussPost(post);
        // 作者
        Member member = memberService.findUserById(post.getUserId());
        discussPostQueryById_z1.setUser(member);
        // 点赞数量
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPostId);
        discussPostQueryById_z1.setLikeCount(likeCount);
        // 点赞状态
        int likeStatus = hostHolder.getMember() == null ? 0 :
                likeService.findEntityLikeStatus(hostHolder.getMember().getId(), ENTITY_TYPE_POST, discussPostId);
        discussPostQueryById_z1.setLikeStatus(likeStatus);

        // 评论: 给帖子的评论
        // 回复: 给评论的评论
        // 评论列表
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());
        List<Comment> commentList = commentMapper.selectAllCommentsByEntity(ENTITY_TYPE_POST, post.getId());
        PageInfo<Comment> pageInfo = new PageInfo<>(commentList);
        pageDto.setTotal(pageInfo.getTotal());
        // 评论VO列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                // 评论VO
                Map<String, Object> commentVo = new HashMap<>();
                // 评论
                commentVo.put("comment", comment);
                // 作者
                commentVo.put("user", memberService.findUserById(comment.getUserId()));
                // 点赞数量
                likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);
                // 点赞状态
                likeStatus = hostHolder.getMember() == null ? 0 :
                        likeService.findEntityLikeStatus(hostHolder.getMember().getId(), ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeStatus", likeStatus);

                // 回复列表
                List<Comment> replyList = commentService.findCommentsByEntity(
                        ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
                // 回复VO列表
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (replyList != null) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        // 回复
                        replyVo.put("reply", reply);
                        // 作者
                        replyVo.put("user", memberService.findUserById(reply.getUserId()));
                        // 回复目标
                        Member target = reply.getTargetId() == null ? null : memberService.findUserById(reply.getTargetId());
                        replyVo.put("target", target);
                        // 点赞数量
                        likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeCount", likeCount);
                        // 点赞状态
                        likeStatus = hostHolder.getMember() == null ? 0 :
                                likeService.findEntityLikeStatus(hostHolder.getMember().getId(), ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeStatus", likeStatus);

                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys", replyVoList);

                // 回复数量
                int replyCount = commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("replyCount", replyCount);

                commentVoList.add(commentVo);
            }
        }
        pageDto.setList(commentVoList);

        discussPostQueryById_z1.setPageDto(pageDto);

        return discussPostQueryById_z1;

    }

    public int updateCommentCount(String id, int commentCount) {
        return myDiscussPostMapper.updateCommentCount(id, commentCount);
    }

    public int updateType(String id, int type) {
        return myDiscussPostMapper.updateType(id, type);
    }

    public int updateStatus(String id, int status) {
        return myDiscussPostMapper.updateStatus(id, status);
    }

    public int updateScore(String id, double score) {
        return myDiscussPostMapper.updateScore(id, score);
    }

}
